﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using SystemSettings;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Model.User;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;

namespace Labthink.PCSoft.UniversalHost4
{
    public partial class ChangePassword
    {
        public string LoginName { get; set; }
        private Window _owner;

        public ChangePassword()
        {
            InitializeComponent();
        }

        private void BtnOK_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(pbCurrentPassword.Pwd.Password) || string.IsNullOrEmpty(pbNewPassword.Pwd.Password) ||
                string.IsNullOrEmpty(pbConfirmPassword.Pwd.Password))
                return;

            var hashedNewPassword = PasswordHash.HashPassword(pbCurrentPassword.Pwd.Password, Common.CurrentUser.Salt);
            if (hashedNewPassword != Common.CurrentUser.Password)
            {
                MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("SD-OldPasswordError"));
                return;
            }

            if (string.Equals(pbCurrentPassword.Pwd.Password, pbNewPassword.Pwd.Password))
            {
                MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("NewPwdCantSameWithCurrent"));
                return;
            }

            if (!string.Equals(pbConfirmPassword.Pwd.Password, pbNewPassword.Pwd.Password))
            {
                MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("NewPwdNotSame"));
                return;
            }

            //密码验证
            if (pbNewPassword.Pwd.Password.Length < Common.SafeInfo.PwdMinLength)
            {
                // MessageBox.Show("新密码长度必须大于?位");
                MyMessageBox.Show(_owner, string.Format(LanguageManager.GetLanguageValue("NewPwdLength"), Common.SafeInfo.PwdMinLength));
                return;
            }

            var complexity = CheckPasswordStrength(pbNewPassword.Pwd.Password);
            if (complexity < Common.SafeInfo.Complexity)
            {
                if (Common.SafeInfo.Complexity == 4)
                {
                    MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("NewPwdRule4"));
                }

                if (Common.SafeInfo.Complexity == 3)
                {
                    MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("NewPwdRule3"));
                }

                return;
            }

            var u = new User
            {
                LoginName = Common.CurrentUser == null ? LoginName : Common.CurrentUser.LoginName,
                Password = pbCurrentPassword.Pwd.Password,
                NewPwd = pbNewPassword.Pwd.Password,
            };

            try
            {
                UserRepository.ChangePassword(u.LoginName, u.NewPwd, ConfigAndSettings.GetSafeInfo().Expires);

                MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("ActionSuccess"));
                if (Common.CurrentUser != null)
                    Common.CurrentUser.Password = u.NewPwd;

                Tag = u.NewPwd;

                // 重新获取
                var  ux = UserRepository.GetUserByLoginName(u.LoginName);
                Common.CurrentUser = ux;
                LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-ChangePwd"), "Manage");
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MyMessageBox.Show(_owner, ex.Message);
            }
        }

        private void ChangePassword_OnLoaded(object sender, RoutedEventArgs e)
        {
            _owner = Window.GetWindow(this);

            Top = (SystemParameters.FullPrimaryScreenHeight - Height) / 2;
            Left = (SystemParameters.FullPrimaryScreenWidth - Width) / 2;
        }

        private void ChangePassword_OnMouseMove(object sender, MouseEventArgs e)
        {
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private static int CheckPasswordStrength(string password)
        {
            int score = 0;
            var specialChars = "~`!@#$%^&*()_+-=|\\{}[]':;\"<>?,./ ";

            if (Regex.Match(password, @"\d+").Success)
                score++;

            if (Regex.Match(password, @"[a-z]").Success)
                score++;

            if (Regex.Match(password, @"[A-Z]").Success)
                score++;

            var canBreak = false;
            foreach (char c in password.TakeWhile(c => !canBreak))
            {
                if (specialChars.Any(ch => c == ch))
                {
                    score++;
                    canBreak = true;
                }
            }

            return score;
        }
    }
}
